<?php

namespace App\Http\Controllers;

use App\Commodity;
use App\Datatables;
use Illuminate\Http\Request;
use Storage;

class CommodityController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
    }

    /**
     * 商品列表
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\JsonResponse|\Illuminate\View\View
     */
    public function commoditiesList(Request $request)
    {
        if ($request->isMethod('post')) {
            return response()->json(Datatables::CommoditiesList());
        }
        return view('commodity.commoditiesList');
    }

    /**
     * 添加商品
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\RedirectResponse|\Illuminate\View\View
     */
    public function commodityPublish(Request $request)
    {
        if ($request->isMethod('post')) {

            $return = Commodity::CommodityPublish($request);
            if ($return['status'] === 1) {
                return redirect('/commodity/commoditiesList')->with('status', $return['status'])->with('message', $return['message']);
            } else {
                return back()->with('status', $return['status'])->with('message', $return['message']);
            }
        }

        return view('commodity.commodityPublish');
    }


    /**
     * 修改商品
     * @param Request $request
     * @param Commodity $commodity
     * @return $this|\Illuminate\Http\RedirectResponse
     */
    public function commodityModify(Request $request, Commodity $commodity)
    {
        if ($request->isMethod('post')) {
            $return = Commodity::CommodityModify($request, $commodity->id);
            return back()->with('status', $return['status'])->with('message', $return['message']);
        }
        return view('commodity.commodityModify')->with(compact('commodity'));
    }

    /**
     * 删除商品
     * @param Commodity $commodity
     * @return array
     * @throws \Exception
     */
    public function commodityDel(Commodity $commodity)
    {
        if (!$commodity->delete()) {
            return ['status' => 2, 'message' => '删除失败'];
        }

        return ['status' => 1, 'message' => '删除成功'];
    }


    /**
     * 删除某张展示图
     * @param Request $request
     * @param Commodity $commodity
     * @return array
     */
    public function commodityPicDel(Request $request, Commodity $commodity)
    {
        $field = $request->field;
        $picUrl = $commodity->$field;
        $picUrl = substr($picUrl, 46);
        //删除oss上的图片
        Storage::disk('oss')->delete($picUrl);
        $commodity->$field = NULL;
        if (!$commodity->save()) {
            return ['status' => 2, 'message' => '删除失败'];
        }
        return ['status' => 1, 'message' => '删除成功'];
    }
}
